package com.yywz.log;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.HTMLLayout;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.WriterAppender;
import org.apache.log4j.xml.DOMConfigurator;

public class TestLog4j {

	private static Logger logger = Logger.getLogger(TestLog4j.class);

	public static void main(String[] args) throws IOException {
		TestLog4j test = new TestLog4j();
		// test.testWriterAppender();
		// test.testConsoleAppender();
		test.testXMLConfigurator();
	}

	public void testFileAppender() throws IOException {

		SimpleLayout layout = new SimpleLayout();

		FileAppender appender = new FileAppender(layout, "log.txt", true);

		logger.addAppender(appender);

		logger.debug("Here is some debug");

		logger.info("Here is some Info");

		logger.warn("Here is some warn", new IOException());

		logger.error("Here is some error");

		logger.fatal("Here is some error");
	}

	public void testWriterAppender() throws FileNotFoundException {

		HTMLLayout layout = new HTMLLayout();

		FileOutputStream output = new FileOutputStream("log.html");

		WriterAppender appender = new WriterAppender(layout, output);

		logger.addAppender(appender);

		logger.setLevel((Level) Level.DEBUG);

		logger.debug("Here is some debug");

		logger.info("Here is some Info");

		logger.warn("Here is some warn", new IOException());

		logger.error("Here is some error");

		logger.fatal("Here is some error");
	}

	public void testConsoleAppender() {

		String pattern = "Milliseconds since program start: %r %n";
		pattern += "Classname of caller %C %n";
		pattern += "Date in ISO8601 format: %d{ISO8601} %n";
		pattern += "Location of log event: %l %n";
		pattern += "Message: %rn %n %n";

		PatternLayout layout = new PatternLayout(pattern);

		ConsoleAppender appender = new ConsoleAppender(layout);

		logger.addAppender(appender);

		logger.setLevel((Level) Level.DEBUG);

		logger.debug("Here is some debug");

		logger.info("Here is some Info");

		logger.warn("Here is some warn", new IOException());

		logger.error("Here is some error");

		logger.fatal("Here is some error");
	}

	public void testXMLConfigurator() {

		DOMConfigurator.configure("log.xml");

		logger.debug("Here is some debug");

		logger.info("Here is some Info");

		logger.warn("Here is some warn", new IOException());

		logger.error("Here is some error");

		logger.fatal("Here is some error");
	}
}
